package com.atguigu.spzx.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.manager.mapper.SysRoleUserMapper;
import com.atguigu.spzx.manager.mapper.SysUserMapper;
import com.atguigu.spzx.manager.service.SysUserService;
import com.atguigu.spzx.model.dto.system.AssginRoleDto;
import com.atguigu.spzx.model.dto.system.LoginDto;
import com.atguigu.spzx.model.dto.system.SysUserDto;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.system.LoginVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.minio.Digest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Author:L枣
 * Date:2024/9/5
 */
@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public LoginVo login(LoginDto loginDto) {

        //1、获取输入验证码和存储到redis的key名称  loginDto获取到
        String captcha = loginDto.getCaptcha();
        String key = loginDto.getCodeKey();

        //2、根据获取的redis里面key  查询redis里面存储的验证码
        String redisCode = redisTemplate.opsForValue().get("user:validate" + key);

        //3、比较输入的验证码和redis存储验证码是否一致
        if (StrUtil.isEmpty(redisCode) || !StrUtil.equalsIgnoreCase(captcha,redisCode)){
            System.out.println(redisCode);
            System.out.println(captcha);
            throw new GuiguException(ResultCodeEnum.VALIDATECODE_ERROR);
        }

        //4、如果不一致，提示用户校验失败

        //5、如果一致，删除redis里面的验证码
        redisTemplate.delete("user:validate:" + key);


        //获取提交过来的用户名
        String userName = loginDto.getUserName();

        //根据用户名查询用户信息
        SysUser sysUser = sysUserMapper.selectUserInfoByUserName(userName);

        //判断用户是否存在
        if (sysUser == null){
//            throw new RuntimeException("用户名或密码错误");
        throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }

        // 判断密码是否正确
        String database_password = sysUser.getPassword();
        String input_password = loginDto.getPassword();
            //把输入的密码先进行加密，再和数据库中的密码进行比较，md5
        input_password = DigestUtils.md5DigestAsHex(input_password.getBytes());
        if (!database_password.equals(input_password)){
//            throw new RuntimeException("密码错误");
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }

        //如果密码正确，登入成功。
        //登入成功，生成token
        String token = UUID.randomUUID().toString().replaceAll("-", "");

        //把登入成功的用户信息保存到redis中
            //key 为token，value为用户信息
        redisTemplate.opsForValue().set("user:login:"+token,
                                            JSON.toJSONString(sysUser),
                                        7,
                                            TimeUnit.DAYS);

        //返回loginVo对象
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);

        return loginVo;
    }

    @Override
    public SysUser getUserInfo(String token) {
        String userJson = redisTemplate.opsForValue().get("user:login:" + token);
        SysUser sysUser = JSON.parseObject(userJson, SysUser.class);
        return sysUser;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login:" + token);
    }

    //用户条件分页查询
    @Override
    public PageInfo<SysUser> findByPage(Integer pageNum, Integer pageSize, SysUserDto sysUserDto) {
        PageHelper.startPage(pageNum,pageSize);
        List<SysUser> list = sysUserMapper.findByPage(sysUserDto);
        PageInfo<SysUser> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public void saveSysUser(SysUser sysUser) {
        //1 判断用户名不能重复
        String userName = sysUser.getUserName();
        SysUser dbSysUser = sysUserMapper.selectUserInfoByUserName(userName);
        if (dbSysUser != null){
            throw new GuiguException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }

        //2 密码进行加密处理
        String md5_password = DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes());
        sysUser.setPassword(md5_password);

        //设置status值  1 表示用户可用  0 表示用户不可用
        sysUser.setStatus(1);

        sysUserMapper.save(sysUser);
    }

    @Override
    public void updateSysUser(SysUser sysUser) {
//        String userName = sysUser.getUserName();
//        SysUser dbSysUser = sysUserMapper.selectUserInfoByUserName(userName);
//        if (dbSysUser != null){
//            throw new GuiguException(ResultCodeEnum.USER_NAME_IS_EXISTS);
//        }
        sysUserMapper.update(sysUser);
    }

    @Override
    public void deleteById(Long userId) {
        sysUserMapper.delete(userId);
    }

    @Override
    public void doAssign(AssginRoleDto assginRoleDto) {
        //1、根据用户id删除之前分配的角色数据
        sysRoleUserMapper.deleteByUserId(assginRoleDto.getUserId());

        //2、重新分配新数据
        List<Long> roleIdList = assginRoleDto.getRoleIdList();
        //遍历集合，获取每个角色id
        for (Long roleId : roleIdList) {
                sysRoleUserMapper.doAssign(assginRoleDto.getUserId(),roleId);
        }
    }
}

